XMLHttpRequest.prototype.sendAsBinary = function (file, param) {
	var formData = new FormData();
	formData.append('key', param.key);
	formData.append('token', param.token);
	formData.append('file', file);
	this.send(formData)
}

var param = {}, xhr = new XMLHttpRequest();
//第一步
function changeAvatarHandle(callback) {
	var pic = document.getElementById('sourceCode'),
		pic_file = pic.files[0],
		pic_name = pic_file.name,
		startIndex = pic_name.lastIndexOf('.') + 1,
		pic_type = pic_name.substring(startIndex);

	var tip = document.getElementById('tip');

	
	if (pic_type != 'apk') {
		tip.style.display = 'block';
		setTimeout(function() {
			tip.className = 'modal fade in';
		}, 100);
		setTimeout(function () {
			tip.className = 'modal fade';
			setTimeout(function() {
				tip.style.display = 'none';
			}, 100);
		}, 2000);
		uploadFile('', '', callback);
	} else {
		//如果已经有拿到token，则不再调用 getUploadParam 方法拿到token
		if(param.key && param.token && param.url){
			uploadFile(pic_file, param, callback);
		}else{
			getUploadParam(pic_type, function (data) {
				uploadFile(pic_file, data, callback);
			});

		}

	}


}
//第二步
function getUploadParam(type, callback) {
	var url = '/assets/request-token?ext_name=' + type;
	if (!type) { callback(false) }

	xhr.open('GET', url, true);
	xhr.send(null);
	xhr.onreadystatechange = function () {
		if (xhr.readyState == 4 && xhr.status == 200) {
			var get_data = JSON.parse(xhr.responseText);
			if(get_data.success){
				param = get_data.data;
				callback(get_data.data);
			}
		}
	}

}
//第三步
function uploadFile(file, param, callback) {

	var upload = xhr.upload;
	// if(progress){
	//     upload.addEventListener("progress", progress, false);
	// }
	
	if(file == ''){
		callback('');
	}else{
		xhr.open("POST", 'http://up.qiniu.com', true);
		xhr.sendAsBinary(file, param);
		xhr.onload = function () {
			if (xhr.responseText) {
				callback(xhr.responseText, xhr)
			}
		};

	}
}

function uploadResult(result) {
	var file_url = 'http://cdn.ifenghuotai.cn/' + JSON.parse(result).key;
}
